package controllers

import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._

import models._
import views._

object Login extends Controller {

  val loginForm = Form(
    tuple(
      "email" -> text,
      "password" -> text
    ) verifying("请输入正确的邮箱和密码", result => result match{
      case (email, password) => User.authenticate(email, password).isDefined
    })
  )

  def login = Action { implicit request =>
    Ok(html.login(loginForm))
  }

  def authenticate = Action { implicit request =>
    loginForm.bindFromRequest.fold(
      formWithError => BadRequest(html.login(formWithError)),
      user => Redirect(routes.Application.index).withSession("email" -> user._1)
    )
  }

  def logout = Action {
    Redirect(routes.Login.login).withNewSession.flashing(
      "success" -> "退出成功"
    )
  }
}


trait Secured {
  private def username(request: RequestHeader) = request.session.get("email")

  private def onUnanthorized(request: RequestHeader) =  Results.Redirect(routes.Login.login)

  def IsAuthenticated(f: => String => Request[AnyContent] => Result) = Security.Authenticated(username,onUnanthorized){
    user =>
      Action(request => f(user)(request))
  }

  def IsMemberOf(project: Long)(f: => String => Request[AnyContent] => Result) = IsAuthenticated{
    user => request =>
      if(User.isMember(project, user)){
        f(user)(request)
      } else {
        Results.Forbidden
      }
  }
}